package com.it.schoolbookshop_back.controller.orders;

import com.it.schoolbookshop_back.entities.dto.OrderGenerateDTO;
import com.it.schoolbookshop_back.entities.dto.OrderPayDTO;
import com.it.schoolbookshop_back.entities.dto.TransactionNotificationDTO;
import com.it.schoolbookshop_back.entities.po.Book;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.entities.po.Transaction;
import com.it.schoolbookshop_back.entities.vo.OrderDetailVO;
import com.it.schoolbookshop_back.entities.vo.OrderGenerateVO;
import com.it.schoolbookshop_back.enums.NotificationType;
import com.it.schoolbookshop_back.mapper.BookMapper;
import com.it.schoolbookshop_back.service.NotificationService;
import com.it.schoolbookshop_back.service.OrderService;
import com.it.schoolbookshop_back.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/orders")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private BookMapper bookMapper;
    
    @Autowired
    private NotificationService notificationService;
    
    /**
     * 获取所有订单
     *
     * @param status 订单状态（可选）
     * @return 订单列表
     */
    @GetMapping
    public Result<Map<String, Object>> getAllOrders(@RequestParam(required = false) String status) {
        try {
            // 从token中获取用户ID
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.unauthorized();
            }
            
            log.info("用户[{}]查询订单列表，状态过滤: {}", userId, status);
            
            // 调用服务获取订单列表
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("orders", orderService.getUserOrders(userId, status));
            
            return Result.success(resultMap);
        } catch (Exception e) {
            log.error("获取订单列表异常: {}", e.getMessage(), e);
            return Result.failed("获取订单列表失败: " + e.getMessage());
        }
    }

    /**
     * 生成订单
     *
     * @param orderGenerateDTO 订单生成请求数据
     * @return 订单生成结果
     */
    @PostMapping("/generate")
    public Result<OrderGenerateVO> generateOrder(@RequestBody OrderGenerateDTO orderGenerateDTO) {
        try {
            // 从token中获取用户ID
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.unauthorized();
            }
            
            log.info("用户[{}]请求生成订单: {}", userId, orderGenerateDTO);
            
            // 参数校验
            if (orderGenerateDTO == null || orderGenerateDTO.getBooks() == null || orderGenerateDTO.getBooks().isEmpty()) {
                return Result.validateFailed("订单书籍信息不能为空");
            }
            
            // 调用服务生成订单
            OrderGenerateVO generatedOrder = orderService.generateOrder(orderGenerateDTO, userId);
            
            if (generatedOrder != null) {
                return Result.success("订单生成成功", generatedOrder);
            } else {
                return Result.failed("订单生成失败");
            }
        } catch (Exception e) {
            log.error("生成订单异常: {}", e.getMessage(), e);
            return Result.failed("生成订单失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     *
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("/orderDetail")
    public Result<OrderDetailVO> getOrderDetail(@RequestParam(name = "order_id", required = true) String orderId) {
        try {
            // 从token中获取用户ID
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.unauthorized();
            }
            
            log.info("用户[{}]查询订单详情，订单号: {}", userId, orderId);
            
            // 调用服务查询订单详情
            OrderDetailVO orderDetail = orderService.getOrderDetail(orderId);
            if (orderDetail == null || orderDetail.getBook() == null || orderDetail.getBook().isEmpty()) {
                return Result.failed("未找到该订单详情");
            }
            
            // 验证该订单是否属于当前用户
            if (!orderService.isOrderBelongsToUser(orderId, userId)) {
                log.warn("用户[{}]尝试查看不属于自己的订单[{}]详情", userId, orderId);
                return Result.forbidden("您无权查看该订单详情");
            }
            
            return Result.success(orderDetail);
        } catch (Exception e) {
            log.error("获取订单详情异常: {}", e.getMessage(), e);
            return Result.failed("获取订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 取消订单
     *
     * @param orderId 订单号
     * @return 操作结果
     */
    @PutMapping("/orderCancel/{order_id}")
    public Result<Object> cancelOrder(@PathVariable("order_id") String orderId) {
        try {
            // 从token中获取用户ID
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.unauthorized();
            }
            
            log.info("用户[{}]请求取消订单: {}", userId, orderId);
            
            // 验证该订单是否属于当前用户
            if (!orderService.isOrderBelongsToUser(orderId, userId)) {
                log.warn("用户[{}]尝试取消不属于自己的订单[{}]", userId, orderId);
                return Result.forbidden("您无权取消该订单");
            }
            
            boolean result = orderService.cancelOrder(orderId);
            if (result) {
                return Result.success("订单取消成功", new HashMap<>());
            } else {
                return Result.failed("订单取消失败，可能订单不存在或已完成/取消");
            }
        } catch (Exception e) {
            log.error("取消订单异常: {}", e.getMessage(), e);
            return Result.failed("取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 支付订单
     *
     * @param orderPayDTO 订单支付请求数据
     * @return 操作结果
     */
    @PatchMapping("/orderPay")
    public Result<Object> payOrder(@RequestBody OrderPayDTO orderPayDTO) {
        if (orderPayDTO == null || orderPayDTO.getOrder_id() == null || orderPayDTO.getOrder_id().trim().isEmpty()) {
            return Result.validateFailed("订单号不能为空");
        }
        
        // 从token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 调用服务层完成支付
            boolean result = orderService.payOrder(orderPayDTO.getOrder_id(), userId);
            
            if (result) {
                // 支付成功，返回结果
                log.info("用户[{}]支付订单[{}]成功", userId, orderPayDTO.getOrder_id());
                
                // 获取订单详情
                OrderDetailVO orderDetail = orderService.getOrderDetail(orderPayDTO.getOrder_id());
                
                if (orderDetail != null && orderDetail.getBook() != null && !orderDetail.getBook().isEmpty()) {
                    // 为每本书籍的卖家创建交易通知
                    for (OrderDetailVO.BookDetail bookDetail : orderDetail.getBook()) {
                        // 尝试从订单详情中获取卖家ID
                        // 注意：这里假设在OrderDetailVO的BookDetail中没有卖家ID，需要单独获取
                        Integer sellerId = orderService.getSellerIdByOrderIdAndBookTitle(
                            orderPayDTO.getOrder_id(), bookDetail.getTitle());
                            
                        if (sellerId != null) {
                            // 创建交易通知
                            notificationService.createNotification(
                                sellerId,
                                NotificationType.TRANSACTION,
                                "您的图书《" + bookDetail.getTitle() + "》已被购买，交易已完成",
                                null  // 这里应该传入交易ID，但暂时传null
                            );
                            
                            log.info("已为卖家(ID:{})创建交易通知，订单号:{}，书籍:{}",
                                sellerId, orderPayDTO.getOrder_id(), bookDetail.getTitle());
                        }
                    }
                }
                
                return Result.success("订单支付成功", new HashMap<>());
            } else {
                return Result.failed("订单支付失败，请检查订单状态或余额是否充足");
            }
        } catch (Exception e) {
            log.error("支付订单异常: {}", e.getMessage(), e);
            return Result.failed("支付订单失败: " + e.getMessage());
        }
    }
}
